#include "historymodel.h"

HistoryModel* HistoryModel::m_instance = nullptr;
QMutex HistoryModel::m_mutex;

HistoryModel *HistoryModel::getInstance()
{
    if(!m_instance)
    {
        QMutexLocker locker(&m_mutex);
        if(!m_instance)
        {
            m_instance = new HistoryModel();
        }
    }
    return m_instance;
}

int HistoryModel::rowCount(const QModelIndex &parent) const {
    Q_UNUSED(parent);
    return m_warningList.size();
}

QVariant HistoryModel::data(const QModelIndex &index, int role) const {
    if (!index.isValid() || index.row() >= m_warningList.size())
        return QVariant();

    const WarningInfo &info = m_warningList[index.row()];
    switch (role) {
    case StartDateRole: return info.startDate;
    case StartTimeRole: return info.startTime;
    case DescriptionRole: return info.disciption;
    case EndTimeRole: return info.endTime;
    case DurationRole: return info.duration;
    default: return QVariant();
    }
}

QHash<int, QByteArray> HistoryModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[StartDateRole] = "startDate";
    roles[StartTimeRole] = "startTime";
    roles[DescriptionRole] = "discripTion";
    roles[EndTimeRole] = "endTime";
    roles[DurationRole] = "duationTime";
    return roles;
}

void HistoryModel::updateHistory(const QVector<WarningInfo> &newHistory) {
    beginResetModel();
    m_warningList = newHistory;
    endResetModel();
}

void HistoryModel::updateWarning(const WarningInfo &info) {
    for (int i = 0; i < m_warningList.size(); ++i) {
        if (m_warningList[i].disciption == info.disciption &&
            m_warningList[i].startTime == info.startTime) {
            m_warningList[i] = info;
            emit dataChanged(index(i), index(i));
            return;
        }
    }
    beginInsertRows(QModelIndex(), m_warningList.size(), m_warningList.size());
    m_warningList.append(info);
    endInsertRows();
}

HistoryModel::HistoryModel(QObject *parent)
    : QAbstractListModel{parent}
{

}

HistoryModel::~HistoryModel()
{

}
